/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.meetingreservation.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.meetinginfo.entity.MeetingInfo;
import vip.xiaonuo.biz.modular.meetingreservation.entity.MeetingReservation;
import vip.xiaonuo.biz.modular.meetinginfo.service.MeetingInfoService;
import vip.xiaonuo.biz.modular.meetingreservation.enums.MeetingReservationStatusEnum;
import vip.xiaonuo.biz.modular.meetingreservation.param.*;
import vip.xiaonuo.biz.modular.meetingreservation.service.MeetingReservationStatusService;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.meetingreservation.mapper.MeetingReservationMapper;
import vip.xiaonuo.biz.modular.meetingreservation.service.MeetingReservationService;
import vip.xiaonuo.dev.api.DevConfigApi;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 会议室预约Service接口实现类
 *
 * @author 沐雨眠竹
 * @date  2025/05/15 10:05
 **/
@Slf4j
@Service
public class MeetingReservationServiceImpl extends ServiceImpl<MeetingReservationMapper, MeetingReservation> implements MeetingReservationService {
    public static final String MEETING_LOCK_PREFIX = "meeting-lock";

    @Resource
    private CommonCacheOperator commonCacheOperator;

    @Resource
    private DevConfigApi devConfigApi;

    @Autowired
    private MeetingInfoService meetingInfoService;

    @Resource
    private MeetingReservationStatusService meetingReservationStatusService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Page<MeetingReservation> page(MeetingReservationPageParam meetingReservationPageParam) {
        QueryWrapper<MeetingReservation> queryWrapper = new QueryWrapper<MeetingReservation>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(meetingReservationPageParam.getTypeId())) {
            queryWrapper.lambda().eq(MeetingReservation::getTypeId, meetingReservationPageParam.getTypeId());
        }
        if(ObjectUtil.isNotEmpty(meetingReservationPageParam.getMeetingName())) {
            queryWrapper.lambda().like(MeetingReservation::getMeetingName, meetingReservationPageParam.getMeetingName());
        }
        if(ObjectUtil.isNotEmpty(meetingReservationPageParam.getUserName())) {
            queryWrapper.lambda().like(MeetingReservation::getUserName, meetingReservationPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(meetingReservationPageParam.getStartReservationDate()) && ObjectUtil.isNotEmpty(meetingReservationPageParam.getEndReservationDate())) {
            queryWrapper.lambda().between(MeetingReservation::getReservationDate, meetingReservationPageParam.getStartReservationDate(), meetingReservationPageParam.getEndReservationDate());
        }
        if(ObjectUtil.isNotEmpty(meetingReservationPageParam.getTimeSlot())) {
            queryWrapper.lambda().eq(MeetingReservation::getTimeSlot, meetingReservationPageParam.getTimeSlot());
        }
        if(ObjectUtil.isNotEmpty(meetingReservationPageParam.getStatus())) {
            queryWrapper.lambda().eq(MeetingReservation::getStatus, meetingReservationPageParam.getStatus());
        }
        if(ObjectUtil.isAllNotEmpty(meetingReservationPageParam.getSortField(), meetingReservationPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(meetingReservationPageParam.getSortOrder());
            queryWrapper.orderBy(true, meetingReservationPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(meetingReservationPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(MeetingReservation::getCreateTime);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(MeetingReservationAddParam meetingReservationAddParam) {
        MeetingReservation meetingReservation = BeanUtil.toBean(meetingReservationAddParam, MeetingReservation.class);
        // redis加锁
        String meetingLock = getMeetingLock(meetingReservationAddParam.getReservationDate(),
                meetingReservationAddParam.getTimeSlot(),
                meetingReservationAddParam.getMeetingName());
        if(meetingLock == null) {
            throw new CommonException("该会议室已被预约，会议室门牌号为：{}", meetingReservationAddParam.getMeetingName());
        }
        try {
            //回查数据库是否被预约
            if (!isMeetingAlreadyReserved(meetingReservationAddParam.getReservationDate(),
                    meetingReservationAddParam.getTimeSlot(),
                    meetingReservationAddParam.getMeetingName())
            ) {
                throw new CommonException("Oops！会议室刚刚已被其他用户预约，预约日期：{}，预约时间段：{}，会议室名称：{}，请重新选择会议室",
                        meetingReservationAddParam.getReservationDate(),
                        meetingReservationAddParam.getTimeSlot(),
                        meetingReservationAddParam.getMeetingName());
            }
            // 回填用户ID
            MeetingReserVationAddUserMeetingID(meetingReservationAddParam, meetingReservation);
            // 自动审核
            MeetingReservation finalMeetingReservation = checkAutoApproval(meetingReservation);

            this.save(finalMeetingReservation);

            // 自动过期并修改预约状态
            if ("已批准".equals(finalMeetingReservation.getStatus())) {
                meetingReservationStatusService.setReservationEndTime(finalMeetingReservation);
            }
        } finally {
            commonCacheOperator.remove(meetingLock);
        }
    }

    /**
     * 获取会议室的锁
     */
    private String getMeetingLock(String reservationDate, String timeSlot, String meetingName) {
        String lockKey = MEETING_LOCK_PREFIX + '_' + reservationDate + '_' + timeSlot + '_' + meetingName + "'_NOT_DELETE'";
        if(commonCacheOperator.get(lockKey) != null) {
            return null;
        }
        commonCacheOperator.put(lockKey, "LOCKED", 300);
        return lockKey;
    }

    /**
     * 在数据库中回查会议室是否已被预约
     */
    private boolean isMeetingAlreadyReserved(String reservationDate, String timeSlot, String meetingName) {
        //回查数据库是否被预约
        QueryWrapper<MeetingReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("RESERVATION_DATE", reservationDate)
                .eq("TIME_SLOT", timeSlot)
                .eq("MEETING_NAME", meetingName)
                .eq("DELETE_FLAG", "NOT_DELETE");
        return this.count(queryWrapper) <= 0;
    }

    /**
     *   添加会议室预约信息时额外保存预约的用户ID和预约的会议室ID
     */
    private void MeetingReserVationAddUserMeetingID(MeetingReservationAddParam meetingReservationAddParam,MeetingReservation meetingReservation){
        String meetingName = meetingReservationAddParam.getMeetingName();
        //根据会议室查会议室门牌号
        QueryWrapper<MeetingInfo> meetingInfoQueryWrapper = new QueryWrapper<>();
        meetingInfoQueryWrapper.eq("name", meetingName);
        MeetingInfo meetingInfo = meetingInfoService.getOne(meetingInfoQueryWrapper);
        if(ObjectUtil.isNull(meetingInfo)) {
            throw new CommonException("会议室不存在，会议室名称为：{}", meetingName);
        }
        //保存会议室门牌号和前端传入的一些参数
        meetingReservation.setMeetingName(meetingInfo.getName());
        //获取当前B端登录用户的ID
        String loginIdAsString = StpUtil.getLoginIdAsString();
        meetingReservation.setUserId(loginIdAsString);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(MeetingReservationEditParam meetingReservationEditParam) {
        MeetingReservation meetingReservation = this.queryEntity(meetingReservationEditParam.getId());
        String oldStatus = meetingReservation.getStatus();

        BeanUtil.copyProperties(meetingReservationEditParam, meetingReservation);
        this.updateById(meetingReservation);

        // 如果状态从非"已批准"变为"已批准"，则设置预约结束时间
        if (!"已批准".equals(oldStatus) && "已批准".equals(meetingReservation.getStatus())) {
            meetingReservationStatusService.setReservationEndTime(meetingReservation);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<MeetingReservationIdParam> meetingReservationIdParamList) {
        List<String> idList = CollStreamUtil.toList(meetingReservationIdParamList, MeetingReservationIdParam::getId);

        // 删除Redis中的过期键
        for (String id : idList) {
            meetingReservationStatusService.removeFromDelayQueue(id);
        }

        // 执行删除
        this.removeByIds(idList);
    }

    @Override
    public void cancel(MeetingReservationIdParam meetingReservationIdParam) {
        QueryWrapper<MeetingReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MeetingReservation::getId, meetingReservationIdParam.getId());
        MeetingReservation meetingReservation = this.getOne(queryWrapper);
        if(ObjectUtil.isEmpty(meetingReservation)) {
            throw new CommonException("会议室预约不存在，id值为：{}", meetingReservationIdParam.getId());
        }
        if(!Objects.equals(meetingReservation.getStatus(), MeetingReservationStatusEnum.COMPLETED.getValue())) {
            meetingReservation.setStatus(MeetingReservationStatusEnum.CANCELLED.getValue());
            this.updateById(meetingReservation);
        }
    }

    @Override
    public MeetingReservation detail(MeetingReservationIdParam meetingReservationIdParam) {
        return this.queryEntity(meetingReservationIdParam.getId());
    }

    @Override
    public MeetingReservation queryEntity(String id) {
        MeetingReservation meetingReservation = this.getById(id);
        if(ObjectUtil.isEmpty(meetingReservation)) {
            throw new CommonException("会议室预约不存在，id值为：{}", id);
        }
        return meetingReservation;
    }

    @Override
    public List<String> getReservedMeeting(MeetingReservationQueryParam param) {
        QueryWrapper<MeetingReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("RESERVATION_DATE", param.getReservationDate())
                .eq("TIME_SLOT", param.getTimeSlot())
                .eq("TYPE_ID", param.getTypeId());

        List<MeetingReservation> reservations = this.list(queryWrapper);

        List<String> res = new ArrayList<>();
        for (MeetingReservation item : reservations) {
            res.add(item.getMeetingName());
        }

        return res;
    }

    /**
     * 检查是否开启自动审核并处理预约信息
     */
    public MeetingReservation checkAutoApproval(MeetingReservation meetingReservation) {
        String autoApprovalFlag = devConfigApi.getValueByKey("BIZ_MEETING_RESERVATION_AUTO_APPROVAL");
        if (Objects.equals(autoApprovalFlag, "true")) {
            meetingReservation.setStatus("已批准");
            meetingReservation.setApproverName("自动审核");
//            meetingReservation.setApprovalTime();
            meetingReservation.setApprovalRemark("系统自动审核通过");
        } else {
            // 未开启自动审核，设置为待审核状态
            meetingReservation.setStatus("待审核");
        }
        return meetingReservation;
    }
}
